import { createRouter, createWebHistory } from 'vue-router'
import {getChannel} from "@/api/group.js";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: () => import('@/pages/login.vue'),
    },
    {
      path: '/loading',
      name: 'loading',
      component: () => import('@/pages/initial.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('@/pages/userProfile/profile.vue'),
    },
    {
      path: '/checkUserProfile/:id?',
      name: 'checkUserProfile',
      component: () => import('@/pages/userProfile/CheckUserProfile.vue'),
    },
    {
      path: '/home',
      name: 'home',
      redirect: '/home/Welcome',
      component: () => import('@/pages/Layout/Layout.vue'),
      children: [
        {
          path: 'friend',
          name: 'friend',
          components: {
            default: () => import('@/pages/friend/FriendView.vue'),
            tabsInfo: () => import('@/pages/Layout/tabsInfo/ConversationList.vue'),
          },
          children: [
            {
              path: '',
              name: 'friend-list',
              components: {
                default: () => import('@/pages/friend/FriendPage.vue'),
              }
            },
            {
              path: ':dmId',
              name: 'conversation',
              components: {
                default: () => import('@/pages/chat/ChatPage.vue'),
              }
            },
          ]
        },
        {
          path: 'Welcome',
          name: 'welcome',
          components: {
            default: () => import('@/pages/welcome/WelcomePage.vue'),
            tabsInfo: () => import('@/pages/Layout/tabsInfo/WelcomeTab.vue')
          }
        },
        {
          path: 'groupChat/:groupId',
          name: 'room',
          redirect: '',
          components: {
            default: () => import('@/pages/channel/channelView.vue'),
            tabsInfo: ()=> import('@/pages/Layout/tabsInfo/GroupInfo.vue')
          },
          children: [
            {
              path: ':channelId',
              name: 'channel',
              components: {
                default: () => import('@/pages/chat/ChatPage.vue'),
              }
            }
          ]
        },
        {
          path: 'webRTC',
          name: 'webRTC',
          components: {
            default: () => import('@/pages/WebRTC.vue'),
            // tabsInfo: () => import('@/components/tabsInfo/ConversationList.vue')
          }
        },
      ]
    }
  ],
})

router.beforeEach(async (to, form, next) => {
  if (to.name === "room" && to.params.groupId) {
    const res = await getChannel(to.params.groupId)
    if (res.status === 200) {
      next(`/home/groupChat/${to.params.groupId}/${res.data[0].id}`)
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
